package com.blackholemax.algorithm.twoPointers;

import java.util.Arrays;

/**
 * 删除有序数组中的重复项2
 */
public class removeDuplicatesII {
    public static int deleteDuplicates(int[] nums) {
        int j = 1; // 写入指针，从第二个元素开始
        for (int i = 2; i < nums.length; i++) {
            if (nums[i] != nums[j - 1]) { // 当前元素与写入指针的前一个不同
                j++;
                nums[j] = nums[i];
            }
        }
        return j + 1; // 因为 j 是索引，长度要 +1
    }

    public static int deleteDuplicates2(int[] nums) {
        int i = 0;
        for (int num : nums) {
            if (i < 2 || num > nums[i - 2]) {
                nums[i++] = num;
            }
        }
        return i;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 2, 3, 3, 3, 4};
        System.out.println(deleteDuplicates(nums));
        System.out.println(Arrays.toString(nums));
    }
}
